<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ws连接测试</title>
    <script src="socket.io.js"></script>
    <link rel="stylesheet" type="text/css" href="index.css" />
</head>

<body>
    <div id="controller">
        <i id="up">↑</i>
        <i id="down">↓</i>
        <i id="left">←</i>
        <i id="right">→</i>
        <i id="A">A</i>
        <i id="B">B</i>
    </div>
    <div id="info">
        连接中...
    </div>

    <script>
        //var invSpeed = 33; //按钮触发频率（敏感度）
        //var ws = io.connect('http://10.8.76.74:9092/');
        var ws = io.connect('http://192.168.31.113:9092/');
        var $info = document.getElementById("info");
        var $controller = document.getElementById("controller");
        //var controlInvs = {};

        //绑定按钮事件
        var $btns = $controller.getElementsByTagName("i");
        for (var i = 0; i < $btns.length; i++) {
            var $btn = $btns[i];
            $btn.addEventListener("touchstart", btnTouchstart);
            $btn.addEventListener("touchend", btnTouchend);
        }

        //按钮触摸开始
        function btnTouchstart(e) {
            e.preventDefault();
            e.target.classList.add("active");
            var action = e.target.id;
            sendControlMessage(action + "+");
            // controlInvs[action] = setInterval(function(){
            //   sendControlMessage(action);
            // },invSpeed)
        }

        //按钮触摸结束
        function btnTouchend(e) {
            e.target.classList.remove("active");
            var action = e.target.id;
            sendControlMessage(action + "-");
            //clearInterval(controlInvs[action])
        }

        //向服务器发送用户操作信息
        function sendControlMessage(msg) {
            ws.emit('controlMessage', msg);
        }

        ws.on('connect', function(data) {
            console.log("controller连接成功");
            console.log(ws);
            $info.innerHTML = "连接成功";
            setTimeout(function() {
                $info.style.display = "none";
            }, 2000)
            //ws.emit('clientMessage', "hello");
        })

        ws.on('error', function() {
            $info.innerHTML = "连接失败！";
            console.log('controller错误:', ws);
            ws.disconnect();
        })
    </script>

</body>

</html>